package com.qiantu.phone.ui.activity;

import static com.qiantu.phone.BuildConfig.OBS_BASE;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.RoomShareBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.HttpBaseData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.manager.OBSManager;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.BottomShareTimeDialog;
import com.qiantu.phone.ui.dialog.BottomTimeDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.utils.GetJsonDataUtil;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class RoomShareInfoActivity extends AppActivity {

    private static final int EDIT_ROOM_CODE = 666;
    private String roomSerialNo;
    private BottomEditDialog mBottomEditDialog;

    private TextView tvShareName;
    private TextView tvBeginTime;
    private TextView tvEndTime;
    private TextView btnShare;
    private View btnShow;
    private BottomShareTimeDialog mBottomTimeDialog;
    private RoomShareBean shareBean;
    private LinearLayout showLayout;
    private LinearLayout showView;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    private SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.sss");

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_share_info;
    }

    @Override
    protected void initView() {
        tvShareName = findViewById(R.id.tv_share_name);
        tvBeginTime = findViewById(R.id.tv_begin_time);
        tvEndTime = findViewById(R.id.tv_end_time);
        btnShare = findViewById(R.id.btn_share);
        showLayout = findViewById(R.id.layout_show_code);
        btnShow = findViewById(R.id.btn_show_code);
        showView = findViewById(R.id.share_view);
//        initViewPager();
        setOnClickListener(R.id.btn_shareto, R.id.btn_begin_time, R.id.btn_end_time,R.id.btn_share,R.id.btn_show_code,R.id.item_wechat,R.id.item_copy_link);
    }


    @Override
    protected void initData() {
        roomSerialNo = getString("roomSerialNo");
        shareBean = getSerializable("data");
        if(shareBean == null){
            shareBean = new RoomShareBean();
            shareBean.setName("入住人");
            Date currentDate = new Date();
            shareBean.setFromTime(simpleDateFormat1.format(currentDate));
            Date endDate = new Date();
            long time = endDate.getTime(); // 获取当前时间的毫秒数
            time += 24 * 60 * 60 * 1000; // 加一天的毫秒数
            endDate.setTime(time);
            shareBean.setToTime(simpleDateFormat1.format(endDate));
            showLayout.setVisibility(View.GONE);
        }else{
            btnShare.setText("保存");
        }
        try {
            Date fromTime = simpleDateFormat1.parse(shareBean.getFromTime());
            Date toTime = simpleDateFormat1.parse(shareBean.getToTime());
            tvBeginTime.setText(simpleDateFormat.format(fromTime));
            tvEndTime.setText(simpleDateFormat.format(toTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tvShareName.setText(shareBean.getName());
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String text = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(text)){
                        toast("请输入分享名称");
                        return;
                    }
                    tvShareName.setText(text);
                    shareBean.setName(text);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel("分享名称");
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.ROOM_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void showBottomTimeDialog(Boolean isBegin) {
        if (mBottomTimeDialog == null) {
            mBottomTimeDialog = new BottomShareTimeDialog(this);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomTimeDialog);
        }
        mBottomTimeDialog.setDialogClickListener(new BottomShareTimeDialog.DialogClickListener() {
            @Override
            public void onConfirmClick(Date date) {
                if(isBegin){
                    shareBean.setFromTime(simpleDateFormat1.format(date));
                    tvBeginTime.setText(simpleDateFormat.format(date));
                }else{
                    shareBean.setToTime(simpleDateFormat1.format(date));
                    tvEndTime.setText(simpleDateFormat.format(date));
                }
            }
        });
        mBottomTimeDialog.setSelectDate(isBegin ? shareBean.getFromTime() : shareBean.getToTime());
        mBottomTimeDialog.show();
    }

    private void shareRoom(){
        if(shareBean.getName().equals("")){
            toast("请先输入名称");
            return;
        }
        LLHttpManager.shareRoom(new ApplicationLifecycle(), AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo(), roomSerialNo, shareBean, new HttpCallback<HttpData<Map<String,String>>>(this) {
            @Override
            public void onSucceed(HttpData<Map<String,String>> result) {
                if(shareBean.getShareSerialNo() != null){
                    finish();
                }else{
                    Map<String,String> map = result.getData();
                    shareBean.setShareUrl(map.get("shareUrl"));
                    shareBean.setAuthCode(map.get("authCode"));
                    showView.setVisibility(View.VISIBLE);
                }
            }
            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void gotoPhotoView(){
        Intent intent = new Intent(this,RoomSharePhotoActivity.class);
        intent.putExtra("data", (Serializable) shareBean);
        intent.putExtra("roomSerialNo",roomSerialNo);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_shareto:
                showBottomEditDialog(shareBean.getName());
                break;
            case R.id.btn_begin_time:
                showBottomTimeDialog(true);
                break;
            case R.id.btn_end_time:
                showBottomTimeDialog(false);
                break;
            case R.id.btn_share:
                if(shareBean.getShareSerialNo() != null){
                    shareRoom();
                }else{
                    shareRoom();
                }
                break;
            case R.id.item_wechat:
            case R.id.btn_show_code:
                gotoPhotoView();
                break;
            case R.id.item_copy_link:
                String url = "";
                String ip = "";
                String ws = "";
                if(HttpBaseData.getInstance().isLocalService()){
                    String[] urls = HttpBaseData.getInstance().getLocalServiceUrl().split(":");
                    url = "http://" + urls[0] + ":30185";
                    ip = "http://" + HttpBaseData.getInstance().getLocalServiceUrl() + "/api";
                    ws = "http://" + HttpBaseData.getInstance().getLocalServiceWs() + "/hubs/linglu";
                }else{
                    url = shareBean.getShareUrl();
                }
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("label",  url + "/?authCode=" + shareBean.getAuthCode() + "&cloudIp=" + ip + "&cloudWsIp=" + ws);
                clipboardManager.setPrimaryClip(clipData);
                toast("已复制到剪贴板");
                break;
        }
    }
}
